import { createRouter, createWebHistory } from 'vue-router'
import login from '../views/login.vue'
import layout from '@/layout/layout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: layout,
      redirect: '/customer-info',
      children: [
        {
          path: '/customer-info',
          name: 'customer-info',
          component: () => import('@/views/customer-info/index.vue'),
          meta: {
            class: '客户管理',
            title: '客户信息',
            icon: 'user',
          },
        },
        {
          path: '/churn_record',
          name: 'churn_record',
          component: () => import('@/views/churn_record/index.vue'),
          meta: {
            class: '客户管理',
            title: '流失记录',
            icon: 'user',
          },
        },
        {
          path: '/business_opportunity',
          name: 'business_opportunity',
          component: () => import('@/views/business_opportunity/index.vue'),
          meta: {
            class: '商机跟进',
            title: '商机管理',
            icon: 'user',
          },
        },
        {
          path: '/business_opportunity_record',
          name: 'business_opportunity_record',
          component: () => import('@/views/business_opportunity_record/index.vue'),
          meta: {
            class: '商机跟进',
            title: '跟进记录',
            icon: 'user',
          },
        },
        {
          path: '/project',
          name: 'project',
          component: () => import('@/views/project/index.vue'),
          meta: {
            class: '产品管理',
            title: '项目管理',
            icon: 'user',
          },
        },
        {
          path: '/project_category',
          name: 'project_category',
          component: () => import('@/views/project_category/index.vue'),
          meta: {
            class: '产品管理',
            title: '项目分类',
            icon: 'user',
          },
        },
        {
          path: '/appointment',
          name: 'appointment',
          component: () => import('@/views/appointment/index.vue'),
          meta: {
            class: '预约管理',
            title: '预约记录',
            icon: 'user',
          },
        },
        {
          path: '/consumption',
          name: 'consumption',
          component: () => import('@/views/consumption/index.vue'),
          meta: {
            class: '消费管理',
            title: '消费记录',
            icon: 'user',
          },
        },
        {
          path: '/revisit_task',
          name: 'revisit_task',
          component: () => import('@/views/revisit_task/index.vue'),
          meta: {
            class: '回访管理',
            title: '回访任务',
            icon: 'user',
          },
        },
        {
          path: '/revisit_record',
          name: 'revisit_record',
          component: () => import('@/views/revisit_record/index.vue'),
          meta: {
            class: '回访管理',
            title: '回访跟进',
            icon: 'user',
          },
        },
        {
          path: '/department',
          name: 'department',
          component: () => import('@/views/department/index.vue'),
          meta: {
            class: '组织管理',
            title: '部门管理',
            icon: 'user',
          },
        },
        {
          path: '/position',
          name: 'position',
          component: () => import('@/views/position/index.vue'),
          meta: {
            class: '组织管理',
            title: '岗位管理',
            icon: 'user',
          },
        },
        {
          path: '/employee',
          name: 'employee',
          component: () => import('@/views/employee/index.vue'),
          meta: {
            class: '组织管理',
            title: '员工管理',
            icon: 'user',
          },
        },
        {
          path: '/user',
          name: 'user',
          component: () => import('@/views/user/index.vue'),
          meta: {
            class: '系统管理',
            title: '用户信息',
            icon: 'user',
          },
        },
        {
          path: '/role',
          name: 'role',
          component: () => import('@/views/role/index.vue'),
          meta: {
            class: '系统管理',
            title: '角色信息',
            icon: 'user',
          },
        },
        {
          path: '/user_ctrl_log',
          name: 'user_ctrl_log',
          component: () => import('@/views/user_ctrl_log/index.vue'),
          meta: {
            class: '系统管理',
            title: '操作日志',
            icon: 'user',
          },
        },
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: login,
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/404.vue'),
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      redirect: '/404'
    },
  ],
})

// 白名单路由（无需登录）
const whiteList = ['/login', '/404']

// // 动态路由注册函数
// const modules = import.meta.glob('../views/**/index.vue')

// function mapRoutes(routes) {
//   return routes.map(route => {
//     const r = {
//       path: route.path,
//       name: route.name,
//       component: modules[`../views/${route.component}/index.vue`],
//     }
//     if (route.children && route.children.length) {
//       r.children = mapRoutes(route.children)
//     }
//     return r
//   })
// }

// // 注册动态路由
// function registerDynamicRoutes() {
//   const localRoutes = localStorage.getItem('router')
//   if (localRoutes) {
//     try {
//       const asyncRoutes = mapRoutes(JSON.parse(localRoutes))
//       asyncRoutes.forEach(route => {
//         if (!router.hasRoute(route.name)) {
//           router.addRoute('layout', route)
//         }
//       })
//       return true
//     } catch (error) {
//       console.error('动态路由注册失败:', error)
//       return false
//     }
//   }
//   return false
// }

router.beforeEach(async (to, from, next) => {
  // 获取 token
  const token = localStorage.getItem('token')

  // 白名单路由直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 没有 token，跳转登录页
  if (!token) {
    next({ name: 'login' })
    return
  }

  // // 有 token，检查是否已注册动态路由
  // const hasDynamicRoutes = router.hasRoute('customer-info') // 检查一个动态路由是否存在

  // if (!hasDynamicRoutes) {
  //   // 注册动态路由
  //   const success = registerDynamicRoutes()
  //   if (success) {
  //     // 重新导航到目标路由（因为路由表已更新）
  //     next({ ...to, replace: true })
  //     return
  //   } else {
  //     // 动态路由注册失败，可能是 token 过期
  //     localStorage.removeItem('token')
  //     localStorage.removeItem('router')
  //     next({ name: 'login' })
  //     return
  //   }
  // }

  // 正常放行
  next()
})

export default router



